package com.qf.nio.serversocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/19
 */
public class ServerTest {
    public static void main(String[] args) {
        try {
            //1.创建ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //2.配置端口
            serverSocketChannel.bind(new InetSocketAddress(8080));
//            serverSocketChannel.configureBlocking(false);   //非阻塞的，默认是true
            System.out.println("服务器启动成功");
            //3.接收客户端的连接
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println("新客户端连接。。。");

            //4.读取发送过来的消息
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024*10);  //创建ByteBuffer
            socketChannel.read(byteBuffer); //把数据读取到byteBuffer中
            System.out.println("服务端读取的内容："+new String(byteBuffer.array()));

            //5.返回数据给客户端
            byteBuffer.put("_服务端".getBytes("utf-8"));
            byteBuffer.flip();
            socketChannel.write(byteBuffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
